<template>
    <ForgotHeader>找回密码</ForgotHeader>
    <div class="forgot-container wrapper">
        <!-- 标题区域开始 -->
        <div class="title-wrap">
            <div class="title" :class="{active: mode == 1}" @click="chooseMode(1)">手机找回</div>
            <div class="title" :class="{active: mode == 2}" @click="chooseMode(2)">邮箱找回</div>
        </div>
        <!-- 标题区域结束 -->

        <!-- 表单区域开始 -->
        <el-form :model="form" :rules="rules" ref="forgotForms" class="form-wrap">
            <template v-if="mode == 1">
                <!-- 手机号 -->
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="form.mobile" size="large" placeholder="请输入手机号" autocomplete="off" :prefix-icon="Iphone" maxlength="11" clearable show-word-limit/>
                </el-form-item>
            </template>

            <template v-else>
                <!-- 邮箱 -->
                <el-form-item label="邮箱" prop="email" label-width="64px">
                    <el-input v-model="form.email" size="large" placeholder="请输入邮箱" autocomplete="off" :prefix-icon="Message" maxlength="30" clearable show-word-limit/>
                </el-form-item>
            </template>

            <!-- 验证码开始 -->
            <el-form-item label="验证码" prop="code">
                <el-input style="width: 200px;margin-right: 10px;" v-model="form.code" size="large" placeholder="请输入验证码" autocomplete="off" :prefix-icon="Lock" maxlength="6" clearable show-word-limit/>

                <el-button
                    v-if="mode == 1"
                    size="large"
                    :disabled="!rightMobile"
                    :color="!rightMobile ? 'gray' : '#27BA9B'"
                    style="--el-button-text-color: #fff;--el-button-hover-text-color: #fff"
                    @click="mobileForgotSendCode">
                    {{time ? '剩余' + time + 's' : '发送验证码'}}
                </el-button>
                <el-button
                    v-else
                    size="large"
                    :disabled="!rightEmail"
                    :color="!rightEmail ? 'gray' : '#27BA9B'"
                    style="--el-button-text-color: #fff;--el-button-hover-text-color: #fff"
                    @click="emailForgotSendCode">
                    {{time ? '剩余' + time + 's' : '发送验证码'}}
                </el-button>
            </el-form-item>

            <div class="forgot-btn-wrap">
                <span @click="showForgotPassword" class="forgot-btn">下 一 步</span>
            </div>
        </el-form>
        <!-- 表单区域结束 -->

        <!-- 找回密码弹层开始 -->
        <el-drawer v-model="drawer" size="28%" :close-on-click-modal="false">
            <template #header>
                <div class="header-wrap">找回密码</div>
            </template>

            <template #default>
                <div class="content-wrap">
                    <el-form :model="form" :rules="drawerRules" ref="formRef" style="width: 100%;">
                        <!-- 新密码 -->
                        <el-form-item label="新密码" :label-width="formLabelWidth" prop="new_password">
                            <el-input v-model="form.new_password" autocomplete="off" maxlength="30"
                show-word-limit clearable placeholder="请输入新密码"/>
                        </el-form-item>

                        <!-- 确认密码 -->
                        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="repassword">
                            <el-input v-model="form.repassword" autocomplete="off" maxlength="30"
                show-word-limit clearable placeholder="请输入确认密码"/>
                        </el-form-item>
                    </el-form>
                </div>
            </template>

            <template #footer>
                <div>
                    <el-button @click="drawer = false">取消</el-button>
                    <el-button type="primary" @click="handlerConfirm">确定</el-button>
                </div>
            </template>
        </el-drawer>
        <!-- 找回密码弹层结束 -->
    </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue'
import { useUserStore } from "@/stores/modules/user"
import { useRouter } from 'vue-router'

import ForgotHeader from './components/ForgotHeader.vue'

import { reqMobileForgotSendCodeAPI, reqEmailForgotSendCodeAPI, reqMobileForgotPasswordAPI, reqEmailForgotPasswordAPI } from "@/apis/user"

import { Lock, Iphone, Message } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'


// ------------------- 定义全局变量开始 -------------------
// 定义用户存储
const userStore = useUserStore()

// 定义路由器
const router = useRouter()

// 表单信息对象
const form = reactive({
    mobile: '',
    email: '',
    code: '',
    new_password: '',
    repassword: ''
})


// 表单
const forgotForms = ref(null)

const formRef = ref(null)

// 模式：1手机找回, 2邮箱找回
const mode = ref(1)

// 手机号正则
const mobilePattern = /^1[3|5|7|8|9]\d{9}$/

// 邮箱正则
const emailPattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/

// 是否显示弹层
const drawer = ref(false)

const formLabelWidth = ref('80px')
// ------------------- 定义全局变量结束 -------------------



// ------------------- 选择找回模式开始 -------------------
const chooseMode = (m) => {
    form.mobile = ''
    form.email = ''
    form.code = ''
    mode.value = m
}
// ------------------- 选择找回模式结束 -------------------



// ------------------ 发送验证码功能开始 ------------------
// 手机号正则验证
const rightMobile = computed(() => {
	return mobilePattern.test(form.mobile)
})

// 邮箱正则验证
const rightEmail = computed(() => {
	return emailPattern.test(form.email)
})

// 手机找回过期时间
const time = ref(0)

// 邮箱找回过期时间
const emailTime = ref(0)

// 手机找回发送验证码
const mobileForgotSendCode = async () => {
	if(time.value == 0) {
		// 请求验证码接口
		await reqMobileForgotSendCodeAPI(form.mobile)
		
        ElNotification({ type: 'success', message: '发送成功'});
		
		time.value = 60
		const intervalId = setInterval(() => {
			time.value--
			if(time.value == 0) {
				clearInterval(intervalId)
			}
		}, 1000)
	}
}

// 邮箱找回发送验证码
const emailForgotSendCode = async () => {
	if(time.value == 0) {
		// 请求验证码接口
		await reqEmailForgotSendCodeAPI(form.email)
		
        ElNotification({ type: 'success', message: '发送成功'});
		
		emailTime.value = 60
		const intervalId = setInterval(() => {
			emailTime.value--
			if(emailTime.value == 0) {
				clearInterval(intervalId)
			}
		}, 1000)
	}
}
// ------------------ 发送验证码功能结束 ------------------



// ------------ 自定义手机号校验规则函数开始 ----------------
const validatorMobile = (rule, value, callback) => {
  
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (mobilePattern.test(value)) {
    callback();
  } else {
    callback(new Error('请输入格式正确的手机号'));
  }
}
// ------------ 自定义手机号校验规则函数结束 ----------------



// ------------ 自定义邮箱校验规则函数开始 ----------------
const validatorEmail = (rule, value, callback) => {
  if (emailPattern.test(value)) {
    callback();
  } else {
    callback(new Error('请输入格式正确的邮箱'));
  }
}
// ------------ 自定义邮箱校验规则函数结束 ----------------



// ----------- 自定义确认密码校验规则函数开始 ----------------
const validatorRepassword = (rule, value, callback) => {
  if (form.new_password == value) {
    callback();
  } else {
    callback(new Error('两次密码不一致'));
  }
}
// ------------ 自定义确认密码校验规则函数结束 ----------------



// --------------------- 校验规则开始 ---------------------
const rules = {
  //规则对象属性:
  //required,代表这个字段务必要校验的
  //min:文本长度至少多少位
  //max:文本长度最多多少位
  //message:错误的提示信息
  //trigger:触发校验表单的时机 change->文本发生变化触发校验,blur:失去焦点的时候触发校验规则
  mobile: [
    { required: true, message: '请输入格式正确的手机号', trigger: 'blur' },
    { trigger: 'blur', validator: validatorMobile }
  ],
  email: [
    { required: true, message: '请输入格式正确的邮箱', trigger: 'blur' },
    { trigger: 'blur', validator: validatorEmail }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}
// --------------------- 校验规则结束 ---------------------



// ----------------- 显示找回密码弹层开始 -----------------
const showForgotPassword = async () => {
    //保证全部表单相校验通过再发请求
    await forgotForms.value.validate();

    form.new_password = ''
    form.repassword = ''
    drawer.value = true
}
// ----------------- 显示找回密码弹层结束 -----------------



// ------------------- 处理找回密码开始 -------------------
// 验证规则
const drawerRules = {
    new_password: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { required: true, min: 6, max: 30, message: '密码长度至少6位', trigger: 'blur' }
    ],
    repassword: [
        { required: true, min: 6, message: '请输入确认密码', trigger: 'blur' },
        { trigger: 'blur', validator: validatorRepassword }
    ],
}

// 处理确认找回密码
const handlerConfirm = async () => {
    // 保证全部表单相校验通过再发请求
    await formRef.value.validate();
    // 手机找回
    if (mode.value == 1) {
        await reqMobileForgotPasswordAPI(form)
    } else {
        await reqEmailForgotPasswordAPI(form)
    }

    ElNotification({ type: 'success', message: '找回密码成功' });
    drawer.value = false
    router.push({path: '/login'})
}
// ------------------- 处理找回密码结束 -------------------
</script>

<style scoped lang="scss">
.forgot-container {
  margin: 20px auto;
  padding: 10px;
  background-color: #fff;
  .title-wrap {
    display: flex;
    justify-content: center;
    height: 60px;
    line-height: 60px;

    cursor: pointer;
    
    font-size: 22px;
    .title {
        margin-right: 20px;
        &:last-child {
            margin-left: 0;
        }
    }
    .active {
        color: $main-color;
        border-bottom: 2px solid $main-color;
    }
  }

  .form-wrap {
    width: 600px;
    margin: 0 auto;
    padding: 20px 0;
    .forgot-btn-wrap {
      display: flex;
      justify-content: center;
      height: 50px;
      line-height: 50px;
      .forgot-btn {
        background-color: $main-color;
        color: #fff;
        width: 200px;
        text-align: center;
        cursor: pointer;
      }
    }
  }

    ::v-deep(.el-drawer__header) {
        margin-bottom: 0;
        padding-bottom: 12px;
        border-bottom: 1px solid #f5f5f5;
    }

    .header-wrap {
        font-weight: bold;
        text-align: center;
    }
}
</style>